﻿using ExcelDataReader;
using FastReport;
using FastReport.DevComponents.DotNetBar;
using JYH.Business;
using JYH.Data;
using JYH.DataAccess;
using JYH.Framework;
using JYH.Model;
using JYH.Model.API;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Services.Description;
using System.Web.UI;

namespace JYH.Web.MES.Controllers
{
    [RoutePrefix("api/WMS")]
    public class WMSController : ApiController
    {
        /// <summary>
        /// 查询收料单生成标签 明细
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="ReciveOrderNO">单据编号，用于模糊查询</param>
        /// <param name="PartnerNO">伙伴信息，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryMaterial_label(int rows, int page, string ReciveOrderNO, string PartnerNO, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<WmsReciveItem> list = new List<WmsReciveItem>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                WmsReciveItemBLL bll = new WmsReciveItemBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(PartnerNO))
                {
                    sql.Append("Where (BasPartnerInfo.PartnerNO Like '%" + PartnerNO + "%' or BasPartnerInfo.PartnerName Like '%" + PartnerNO + "%') ");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(ReciveOrderNO))
                {
                    sql.Append("Where WmsReciveOrderInfo.ReciveOrderNO Like '%" + ReciveOrderNO + "%'");
                }

                // 过滤掉状态为 '99' 的记录（可能是已删除或无效状态）
                sql.Append("Where WmsReciveOrderInfo.RState >='1' And WmsReciveOrderInfo.RState<>'99' And WmsReciveItem.LabelQty>0");

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("WmsReciveOrderInfo.ReciveOrderNO,CONVERT(int,ISNULL(WmsReciveItem.ERPItem,0)) ");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);
                list = list.FindAll(p => p.LabelQty > 0).ToList();
                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<WmsReciveItem>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 查询收料单明细内部检索
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="ReciveOrderID">单据ID，查询</param>
        /// <param name="MaterialNO">物料信息，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryReciveOrderItem(int rows, int page, string ReciveOrderID, string MaterialNO, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<WmsReciveItem> list = new List<WmsReciveItem>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                WmsReciveItemBLL bll = new WmsReciveItemBLL();
                sql.Append("Where WmsReciveItem.ReciveOrderID = '" + ReciveOrderID + "'");
                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where (BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%' or BasMaterialInfo.MaterialName Like '%" + MaterialNO + "%') ");
                }

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" WmsReciveItem." + sort + "  " + order);
                }
                else
                {
                    //CONVERT(INT, '456')ISNULL(字段名, 0)
                    // 默认按创建时间升序排序
                    sql.OrderBy("WmsReciveOrderInfo.ReciveOrderNO Desc,  CONVERT(INT,ISNULL( WmsReciveItem.ERPItem,'0') ) ");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<WmsReciveItem>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 查询收料单全信息
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="ReciveOrderNO">单据编号，用于模糊查询</param>
        /// <param name="PartnerNO">伙伴名称，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryWmsReciveOrderInfo(int rows, int page, string ReciveOrderNO, string PartnerNO, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<WmsReciveOrderInfo> list = new List<WmsReciveOrderInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                WmsReciveOrderInfoBLL bll = new WmsReciveOrderInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(ReciveOrderNO))
                {
                    sql.Append("Where WmsReciveOrderInfo.ReciveOrderNO Like '%" + ReciveOrderNO + "%'");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(PartnerNO))
                {
                    sql.Append("Where (BasPartnerInfo.PartnerNO Like '%" + PartnerNO + "%' or BasPartnerInfo.PartnerName Like '%" + PartnerNO + "%')");
                }

                // 过滤掉状态为 '99' 的记录（可能是已删除或无效状态）
                sql.Append("Where WmsReciveOrderInfo.RState <>'99'");

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" WmsReciveOrderInfo." + sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("WmsReciveOrderInfo.ReciveOrderNO  desc");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<WmsReciveOrderInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        ///  保存采购收料主档
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveWmsReciveOrderInfo([FromBody] WmsReciveOrderInfo info)
        {
            ResponseJson<WmsReciveOrderInfo> message = new ResponseJson<WmsReciveOrderInfo>()
            {
                Items = new List<WmsReciveOrderInfo>()
            };
            WmsReciveOrderInfoBLL WmsReciveInfo = new WmsReciveOrderInfoBLL();
            try
            {
                if (!WmsReciveInfo.SaveWmsReciveOrderInfo(info, ref message))
                {
                    return Content(HttpStatusCode.InternalServerError, message.Message);
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(message);
        }

        /// <summary>
        /// 删除收料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteWmsReciveOrderInfo([FromBody] List<WmsReciveOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                WmsReciveOrderInfoBLL bll = new WmsReciveOrderInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.ReciveOrderID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update WmsReciveOrderInfo Set RState='99' Where  WmsReciveOrderInfo.ReciveOrderID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 审核收料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CheckWmsReciveOrderInfo([FromBody] List<WmsReciveOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                WmsReciveOrderInfoBLL bll = new WmsReciveOrderInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.ReciveOrderID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update WmsReciveOrderInfo Set RState='1' Where  WmsReciveOrderInfo.ReciveOrderID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 反审核收料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpCheckWmsReciveOrderInfo([FromBody] List<WmsReciveOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                WmsReciveOrderInfoBLL bll = new WmsReciveOrderInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.ReciveOrderID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update WmsReciveOrderInfo Set RState='0' Where  WmsReciveOrderInfo.ReciveOrderID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        private string GetFileName(HttpContentHeaders headers)
        {
            if (headers.ContentDisposition?.FileName != null)
            {
                return headers.ContentDisposition.FileName.Trim('\"');
            }

            // 兼容不同浏览器（如 Chrome 新版本使用 FileNameStar）
            if (headers.ContentDisposition?.FileNameStar != null)
            {
                return headers.ContentDisposition.FileNameStar;
            }

            return "unknown.xls";
        }

        /// <summary>
        /// 收料明细导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IHttpActionResult> Import()
        {
            var message = new ResponseJson<WmsReciveItem>
            {
                Items = new List<WmsReciveItem>(),
                Code = 200,
                Message = "导入成功"
            };

            if (!Request.Content.IsMimeMultipartContent())
            {
                return Content(HttpStatusCode.InternalServerError, BadRequest());
            }

            try
            {
                WmsReciveItemBLL reciveItemBLL = new WmsReciveItemBLL();
                // 使用 MultipartMemoryStreamProvider 将文件内容保留在内存中
                var provider = new MultipartMemoryStreamProvider();
                // 异步读取上传内容到内存流
                await Request.Content.ReadAsMultipartAsync(provider);
                // 获取第一个上传的文件流
                if (provider.Contents.Count == 0)
                {
                    return Content(HttpStatusCode.InternalServerError, "无文件");
                }
                string reciveOrderID = string.Empty;
                //获取文件名用于判断扩展名
                string filename = string.Empty;
                // 从内存中读取流
                Stream stream = null;
                foreach (var content in provider.Contents)
                {
                    var headers = content.Headers;
                    var contentDisposition = headers.ContentDisposition;

                    if (contentDisposition == null) continue;

                    // 获取表单字段 ReciveOrderID
                    if (contentDisposition.Name?.Trim('\"') == "ReciveOrderID")
                    {
                        reciveOrderID = await content.ReadAsStringAsync();
                    }
                    // 获取上传的文件
                    else if (contentDisposition.FileName != null)
                    {
                        filename = GetFileName(headers);
                        stream = await content.ReadAsStreamAsync();
                    }
                }
                //var fileContent = provider.Contents[0];
                //var ReciveOrderID = provider.Contents[1];

                #region 文件上传导入逻辑

                StringBuilder sb = new StringBuilder();
                Sql sql = new Sql();
                string Msg = string.Empty;
                List<WmsReciveItem> Itemlist = new List<WmsReciveItem>();
                // 判断文件类型（xls/xlsx）
                bool isXls = filename.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
                bool isXlsx = filename.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase);

                if (!isXls && !isXlsx)
                {
                    return Content(HttpStatusCode.InternalServerError, "请上传 Excel 文件（.xls 或 .xlsx）");
                }
                // 使用 ExcelDataReader 读取 Excel 流
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true // 使用第一行作为列头
                        }
                    });
                    DataTable table = result.Tables.Count > 0 ? result.Tables[0] : null;
                    if (!reciveItemBLL.FileDataTable(table, reciveOrderID, ref message))
                    {
                        return Content(HttpStatusCode.InternalServerError, message.Message);
                    }
                    else
                    {
                        message.Message = $"成功导入 {message.TotalCount} 条记录";
                    }
                }

                #endregion 文件上传导入逻辑
            }
            catch (Exception ex)
            {
                message.Message = "导入失败：" + ex.Message;
                return Content(HttpStatusCode.InternalServerError, message.Message);
            }
            return Ok(message);
        }

        /// <summary>
        /// 调拨明细导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IHttpActionResult> DBImport()
        {
            var message = new ResponseJson<WmsTradeSource>
            {
                Items = new List<WmsTradeSource>(),
                Code = 200,
                Message = "导入成功"
            };

            if (!Request.Content.IsMimeMultipartContent())
            {
                return Content(HttpStatusCode.InternalServerError, "不支持的媒体类型");
            }

            try
            {
                WmsTradeSourceBLL reciveItemBLL = new WmsTradeSourceBLL();
                // 使用 MultipartMemoryStreamProvider 将文件内容保留在内存中
                var provider = new MultipartMemoryStreamProvider();
                // 异步读取上传内容到内存流
                await Request.Content.ReadAsMultipartAsync(provider);
                // 获取第一个上传的文件流
                if (provider.Contents.Count == 0)
                {
                    return Content(HttpStatusCode.InternalServerError, "file is null");
                }
                string TradeOrderID = string.Empty;
                //获取文件名用于判断扩展名
                string filename = string.Empty;
                // 从内存中读取流
                Stream stream = null;
                foreach (var content in provider.Contents)
                {
                    var headers = content.Headers;
                    var contentDisposition = headers.ContentDisposition;

                    if (contentDisposition == null) continue;

                    // 获取表单字段 TradeOrderID
                    if (contentDisposition.Name?.Trim('\"') == "TradeOrderID")
                    {
                        TradeOrderID = await content.ReadAsStringAsync();
                    }
                    // 获取上传的文件
                    else if (contentDisposition.FileName != null)
                    {
                        filename = GetFileName(headers);
                        stream = await content.ReadAsStreamAsync();
                    }
                }
                //var fileContent = provider.Contents[0];
                //var ReciveOrderID = provider.Contents[1];

                #region 文件上传导入逻辑

                StringBuilder sb = new StringBuilder();
                Sql sql = new Sql();
                string Msg = string.Empty;
                List<WmsTradeSource> Itemlist = new List<WmsTradeSource>();
                // 判断文件类型（xls/xlsx）
                bool isXls = filename.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
                bool isXlsx = filename.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase);

                if (!isXls && !isXlsx)
                {
                    return Content(HttpStatusCode.InternalServerError, "Please upload an Excel file（.xls or .xlsx）");
                }
                // 使用 ExcelDataReader 读取 Excel 流
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true // 使用第一行作为列头
                        }
                    });
                    DataTable table = result.Tables.Count > 0 ? result.Tables[0] : null;
                    if (!reciveItemBLL.DBFileDataTable(table, TradeOrderID, ref message))
                    {
                        return Content(HttpStatusCode.InternalServerError, message.Message);
                    }
                    else
                    {
                        message.Message = $"Successfully imported {message.TotalCount} records";
                    }
                }

                #endregion 文件上传导入逻辑
            }
            catch (Exception ex)
            {
                message.Message = "Error：" + ex.Message;
                return Content(HttpStatusCode.InternalServerError, message.Message);
            }
            return Ok(message);
        }

        /// <summary>
        ///  保存交易单主档
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveTradeInfo([FromBody] WmsTradeOrderInfo info)
        {
            ResponseJson<WmsTradeOrderInfo> message = new ResponseJson<WmsTradeOrderInfo>()
            {
                Items = new List<WmsTradeOrderInfo>()
            };
            WmsTradeOrderInfoBLL WmsReciveInfo = new WmsTradeOrderInfoBLL();
            try
            {
                if (!WmsReciveInfo.SaveWmsOrderInfo(info, ref message))
                {
                    return Content(HttpStatusCode.InternalServerError, message.Message);
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(message);
        }

        /// <summary>
        /// 检索交易单
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="ProductName">产品名称</param>
        /// <param name="TradeOrderNO">交易单NO</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryWmsTradeOrderInfo(int rows, int page, string order, string sort, string TradeOrderNO, string BeginTime, string EndTime, int TradeType)
        {
            Sql sql = new Sql();
            List<WmsTradeOrderInfo> list = new List<WmsTradeOrderInfo>();
            var lists = "";
            string Msg = string.Empty;
            long total = -1;
            try
            {
                WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();

                sql = new Sql();
                switch (TradeType)
                {
                    case 0:
                        // 收料入库单
                        break;

                    case 1:
                        // 收料退库单
                        break;

                    case 2:
                        // 生产退料单
                        break;

                    case 3:
                        // 生产领料单
                        sql.Append(bll.MFGSqlSelect);
                        break;

                    //case 4:
                    //    // 生产退料单
                    //    break;

                    case 5:
                        // 物料调拨单
                        sql.Append(bll.DbSqlSelect);
                        break;

                    case 6:
                        // 其他领料单
                        break;

                    case 7:
                        // 其他入库单
                        break;

                    case 8:
                        // 生产缴库单
                        break;

                    case 9:
                        // 生产退库单
                        break;

                    case 10:
                        // 销售出库单
                        break;

                    case 11:
                        // 销售退库单
                        break;

                    case 12:
                        // 盘盈盘库单
                        break;

                    case 13:
                        // 生产备料单
                        sql.Append(bll.DbSqlSelect);
                        break;

                    default:
                        // 处理未知类型的交易单
                        break;
                }
                if (!string.IsNullOrEmpty(TradeOrderNO))
                {
                    sql.Append("Where WmsTradeOrderInfo.TradeOrderNO Like '%" + TradeOrderNO + "%'");
                }
                if (!string.IsNullOrEmpty(BeginTime))
                {
                    sql.Append("Where WmsTradeOrderInfo.TradeDate >= '%" + BeginTime + "%'");
                }
                if (!string.IsNullOrEmpty(EndTime))
                {
                    sql.Append("Where WmsTradeOrderInfo.TradeDate <= '%" + EndTime + "%'");
                }
                sql.Append("Where WmsTradeOrderInfo.RState <>'99'");
                sql.Append($"Where WmsTradeOrderInfo.TradeType='{TradeType}'");

                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" WmsTradeOrderInfo." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("WmsTradeOrderInfo.CreateTime desc");
                }
                list = bll.PagedQuery(sql, page, rows, out total, out Msg);
                var json = ConvertJson<WmsTradeOrderInfo>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                return Content(HttpStatusCode.InternalServerError, new { total = total, rows = new List<object>() });
            }
            return Ok(lists);
        }

        /// <summary>
        /// 删除交易单
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteWmsTradeOrderInfo([FromBody] List<WmsTradeOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.TradeOrderID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update WmsTradeOrderInfo Set RState='99' Where  WmsTradeOrderInfo.TradeOrderID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 审核交易单
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CheckWmsTradeOrderInfo([FromBody] List<WmsTradeOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                if (info == null || info.Count() == 0)
                {
                    Msg = "NO Form";
                    return Ok(Msg);
                }
                int TradeType = info[0].TradeType;
                switch (TradeType)
                {
                    default:
                        WmsTradeOrderInfoBLL.CheckTradeOrder(info, SysUserInfoBLL.GetCookieUser().UserNO, out Msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 反审核交易单
        /// 0 收料入库单   1 收料退库单   2 生产领料单    3 收料退库单
        /// 4 生产退料单   5 物料调拨单   6 其他领料单    7 其他入库单
        /// 8 生产缴库单   9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpCheckWmsTradeOrderInfo([FromBody] List<WmsTradeOrderInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                if (info == null || info.Count() == 0)
                {
                    Msg = "NO Form";
                    return Ok(Msg);
                }
                int TradeType = info[0].TradeType;

                switch (TradeType)
                {
                    default:
                        WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();
                        string Ids = "";
                        foreach (var item in info)
                        {
                            Ids += "'" + item.TradeOrderID + "',";
                        }
                        Ids = Ids.Substring(0, Ids.Length - 1);
                        sb.Append("Update WmsTradeOrderInfo Set RState='0' Where  WmsTradeOrderInfo.TradeOrderID in (" + Ids + ")");
                        if (sb.Length > 0)
                            bll.myDataBase.Execute(sb.ToString());
                        break;

                    case 3:
                        WmsProductionPickingOrderBLL.UpCheckWmsTradeOrderInfo(info, SysUserInfoBLL.GetCookieUser().UserNO, out Msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 登账交易单
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult AccountWmsTradeOrderInfo([FromBody] WmsTradeOrderInfo info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();
                bool falg = false;
                info.ApproveUser = SysUserInfoBLL.GetCookieUser().UserNO;
                switch (info.TradeType)
                {
                    case 0:
                        // 收料入库单
                        break;

                    case 1:
                        // 收料退库单
                        break;

                    case 2:
                        // 生产退料单
                        break;

                    case 3:
                        // 生产领料单
                        falg = WmsProductionPickingOrderBLL.AccountWmsTradeOrderInfo(info, out Msg);
                        break;

                    //case 4:
                    //    // 生产退料单
                    //    break;

                    case 5:
                        // 物料调拨单
                        falg = bll.AccountWmsTradeOrderInfo_5(info, out Msg);
                        break;

                    case 6:
                        // 其他领料单
                        break;

                    case 7:
                        // 其他入库单
                        break;

                    case 8:
                        // 生产缴库单
                        break;

                    case 9:
                        // 生产退库单
                        break;

                    case 10:
                        // 销售出库单
                        break;

                    case 11:
                        // 销售退库单
                        break;

                    case 12:
                        // 盘盈盘库单
                        break;

                    default:
                        // 处理未知类型的交易单
                        break;
                }
                if (falg)
                    return Ok();
                else
                    return Content(HttpStatusCode.InternalServerError, Msg);
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }

        /// <summary>
        /// 检索交易单来源明细
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryWmsTradeSource(int rows, int page, string order, string sort, string TradeOrderID, string MaterialNO)
        {
            Sql sql = new Sql();
            List<WmsTradeSource> list = new List<WmsTradeSource>();
            var lists = "";
            string Msg = string.Empty;
            long total = -1;
            try
            {
                WmsTradeSourceBLL bll = new WmsTradeSourceBLL();

                sql = new Sql();
                sql.Append(bll.SqlSelect);
                sql.Append("Where WmsTradeSource.TradeOrderID ='" + TradeOrderID + "'");
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where (BasMaterialInfo.MaterialName Like '%" + MaterialNO + "%' or BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%')");
                }
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    switch (sort)
                    {
                        default:
                            sql.OrderBy(" WmsTradebarcode." + sort + "  " + order);
                            break;

                        case "MaterialNO":
                            sql.OrderBy("  BasMaterialInfo." + sort + "  " + order);
                            break;

                            //case "StorageNO":
                            //    sql.OrderBy("  BasStorageInfo." + sort + "  " + order);
                            //    break;
                    }
                }
                else
                {
                    sql.OrderBy("WmsTradeOrderInfo.TradeOrderNO, CONVERT(INT,ISNULL( WmsTradeSource.ERPItem,'0') )  desc");
                }
                // list = bll.PagedQuery(sql, page, rows, out total, out Msg);

                // list = bll.PagedQuery(page, rows, sql, out total, out Msg);
                list = bll.PagedQuery(sql, page, rows, out total, out Msg);
                var json = ConvertJson<WmsTradeSource>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                return Content(HttpStatusCode.InternalServerError, new { total = total, rows = new List<object>() });
            }
            return Ok(lists);
        }

        /// <summary>
        /// 检索交易单 入库条码明细
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryWmsTradebarcode(int rows, int page, string order, string sort, string TradeOrderID, string MaterialNO)
        {
            Sql sql = new Sql();
            List<WmsTradebarcode> list = new List<WmsTradebarcode>();
            var lists = "";
            string Msg = string.Empty;
            long total = -1;
            try
            {
                WmsTradebarcodeBLL bll = new WmsTradebarcodeBLL();

                sql = new Sql();
                sql.Append(bll.SqlSelect);
                sql.Append("Where (WmsTradeOrderInfo.TradeOrderID ='" + TradeOrderID + "' or WmsTradeOrderInfo.TradeOrderNO='" + TradeOrderID + "')");
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where (BasMaterialInfo.MaterialName Like '%" + MaterialNO + "%' or BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%' or BasBarcodeInfo.BarcodeNO Like '%" + MaterialNO + "%')");
                }

                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    switch (sort)
                    {
                        default:
                            sql.OrderBy(" WmsTradebarcode." + sort + "  " + order);
                            break;

                        case "MaterialNO":
                            sql.OrderBy("  BasMaterialInfo." + sort + "  " + order);
                            break;

                        case "LampNO":
                            sql.OrderBy("  BasLampInfo." + sort + "  " + order);
                            break;

                        case "BarcodeNO":
                            sql.OrderBy("  BasBarcodeInfo." + sort + "  " + order);
                            break;
                    }
                }
                else
                {
                    sql.OrderBy("WmsTradeOrderInfo.TradeOrderNO,BasBarcodeInfo.BarcodeNO");
                }
                list = bll.PagedQuery(sql, page, rows, out total, out Msg);
                var json = ConvertJson<WmsTradebarcode>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                return Content(HttpStatusCode.InternalServerError, new { total = total, rows = new List<object>() });
            }
            return Ok(lists);
        }

        /// <summary>
        /// 依据收料项次删除物料条码(重置打印物料数量，做过交易的条码无法删除)
        /// </summary>
        /// <param name="info">收料项次代码</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage ResetReceiveOrderItem([FromBody] WmsReciveItem info)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<object>();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();
            try
            {
                BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();
                List<BasBarcodeInfo> Barcodes = new List<BasBarcodeInfo>();
                WmsReciveItem reciveItem = new WmsReciveItem();
                Sql sql = new Sql();
                sql.Append(@";Select WmsReciveItem.* ,WmsReciveOrderInfo.ReciveOrderNO
                            From WmsReciveItem
                            Inner JOIn WmsReciveOrderInfo
                            ON WmsReciveItem.ReciveOrderID=WmsReciveOrderInfo.ReciveOrderID");
                sql.Where("WmsReciveItem.ReciveItemID='" + info.ReciveItemID + "'");
                reciveItem = db.FirstOrDefault<WmsReciveItem>(sql.SQL, null);
                if (reciveItem == null)
                {
                    json.Code = 500;
                    json.Message = "Failed:No Records";
                }
                else
                {
                    reciveItem.BatchNO = info.BatchNO;
                    reciveItem.ReciveQty = info.ReciveQty;
                    reciveItem.LabelQty = reciveItem.ReciveQty;

                    db.Execute(BusinessTool.GetUpdateSql(reciveItem));
                    string Msg = string.Empty;
                    Barcodes = bll.GetBarcodeByReceiveOrder(db, reciveItem.ReciveOrderNO, reciveItem.ReciveItemID, out Msg);
                    if (Barcodes != null && Barcodes.Count > 0)
                    {
                        bool res = bll.DeleteBarcode(Barcodes, db, out Msg);
                        if (!res)
                        {
                            json.Message = Msg;
                            json.Code = 500;
                            db.AbortTransaction();
                        }
                        else
                        {
                            db.CompleteTransaction();
                        }
                    }
                    else
                    {
                        db.CompleteTransaction();
                    }
                }
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                json.Message = ex.ToString();
                json.Code = 500;
            }
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 仓库库存条码信息接口
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryWmsStockBarCode(int rows, int page, string order, string sort, string StorageNO, string MaterialNO, string BarcodeNO, string BeginTime, string EndTime, string WarehouseID, string IsLock)
        {
            Sql sql = new Sql();
            Sql sqlInt = new Sql();

            List<WmsStockBarcode> list = new List<WmsStockBarcode>();
            var lists = "";
            string Msg = string.Empty;
            long total = -1;
            try
            {
                WmsStockBarcodeBLL bll = new WmsStockBarcodeBLL();

                sql = new Sql();
                sql.Append(bll.SqlSelect);
                if (!string.IsNullOrEmpty(BarcodeNO))
                {
                    sql.Append("Where BasBarcodeInfo.BarcodeNO like '%" + BarcodeNO + "%'");
                }
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where (BasMaterialInfo.MaterialName Like '%" + MaterialNO + "%' or BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%')");
                }
                if (!string.IsNullOrEmpty(StorageNO))
                {
                    sql.Append("Where (BasStorageInfo.StorageNO Like '%" + StorageNO + "%')");
                }
                if (!string.IsNullOrEmpty(WarehouseID))
                {
                    sql.Append("Where (BasWarehouseInfo.WarehouseID = '" + WarehouseID + "')");
                }
                if (!string.IsNullOrEmpty(IsLock))
                {
                    sql.Append("Where WmsStockBarcode.IsLock = '" + IsLock + "'");
                }
                if (!string.IsNullOrEmpty(BeginTime))
                {
                    sql.Append("Where WmsStockBarcode.CreateTime >= '" + BeginTime + "'");
                }
                if (!string.IsNullOrEmpty(EndTime))
                {
                    sql.Append("Where WmsStockBarcode.CreateTime <= '" + EndTime + "'");
                }
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" WmsStockBarcode." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("WmsStockBarcode.CreateTime desc");
                }
                list = bll.PagedQuery(sql, page, rows, out total, out Msg);
                var json = ConvertJson<WmsStockBarcode>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                return Content(HttpStatusCode.InternalServerError, new { total = total, rows = new List<object>() });
            }
            return Ok(lists);
        }

        /// <summary>
        /// 仓库库存产品物料信息接口
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryWmsStockMaterInfo(int rows, int page, string order, string sort, string StorageNO, string MaterialNO, string BarcodeNO, string BeginTime, string EndTime, string WarehouseID)
        {
            Sql sql = new Sql();
            List<WmsStockMaterial> list = new List<WmsStockMaterial>();
            var lists = "";
            string Msg = string.Empty;
            long total = -1;
            try
            {
                WmsStockMaterialBLL bll = new WmsStockMaterialBLL();

                sql = new Sql();
                sql.Append(bll.SqlSelect);
                if (!string.IsNullOrEmpty(BarcodeNO))
                {
                    sql.Append("Where BasBarcodeInfo.BarcodeNO like '%" + BarcodeNO + "%'");
                }
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where (BasMaterialInfo.MaterialName Like '%" + MaterialNO + "%' or BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%')");
                }
                if (!string.IsNullOrEmpty(StorageNO))
                {
                    sql.Append("Where (BasStorageInfo.StorageNO Like '%" + StorageNO + "%')");
                }
                if (!string.IsNullOrEmpty(WarehouseID))
                {
                    sql.Append("Where (BasWarehouseInfo.WarehouseID = '" + WarehouseID + "')");
                }
                if (!string.IsNullOrEmpty(BeginTime))
                {
                    sql.Append("Where WmsStockMaterial.CreateTime >= '" + BeginTime + "'");
                }
                if (!string.IsNullOrEmpty(EndTime))
                {
                    sql.Append("Where WmsStockMaterial.CreateTime <= '" + EndTime + "'");
                }
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" WmsStockMaterial." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("WmsStockMaterial.CreateTime desc");
                }
                list = bll.PagedQuery(sql, page, rows, out total, out Msg);
                var json = ConvertJson<WmsStockMaterial>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                return Content(HttpStatusCode.InternalServerError, new { total = total, rows = new List<object>() });
            }
            return Ok(lists);
        }

        /// <summary>
        ///  库存锁定解除
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult RelieveIsLock([FromBody] List<WmsStockBarcode> info)
        {
            ResponseJson<WmsStockBarcode> message = new ResponseJson<WmsStockBarcode>()
            {
                Items = new List<WmsStockBarcode>()
            };
            WmsStockBarcodeBLL WmsReciveInfo = new WmsStockBarcodeBLL();
            try
            {
                if (!WmsReciveInfo.RelieveIsLock(info, ref message))
                {
                    return Content(HttpStatusCode.InternalServerError, message.Message);
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(message);
        }

        /// <summary>
        ///  保存领料来源明细
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveSouceItem([FromBody] WmsTradeSource info)
        {
            ResponseJson<WmsTradeSource> message = new ResponseJson<WmsTradeSource>()
            {
                Items = new List<WmsTradeSource>()
            };
            WmsTradeSourceBLL WmsReciveInfo = new WmsTradeSourceBLL();
            try
            {
                if (!WmsReciveInfo.SaveSouceItem(info, ref message))
                {
                    return Content(HttpStatusCode.InternalServerError, message.Message);
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(message);
        }

        /// <summary>
        /// 删除交易单来源明细
        /// 0 收料入库单   1 收料退库单   2 生产领料单    3 收料退库单
        /// 4 生产退料单   5 物料调拨单   6 其他领料单    7 其他入库单
        /// 8 生产缴库单   9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteWmsTradeSource([FromBody] List<WmsTradeSource> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.TradeSourceID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("delete WmsTradeSource Where  WmsTradeSource.TradeSourceID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 回抛ERP
        /// 0 收料入库单   1 收料退库单   3 生产领料单    2 收料退库单
        ///  5 物料调拨单   6 其他领料单    7 其他入库单 8 生产缴库单
        ///  9 生产退库单   10 销售出库单   11 销售退库单  12 盘盈盘库单 13 生产备料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult BackToERP([FromBody] WmsTradeOrderInfo info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功";
            try
            {
                WmsTradeOrderInfoBLL bll = new WmsTradeOrderInfoBLL();
                bool falg = false;

                switch (info.TradeType)
                {
                    case 0:
                        // 收料入库单
                        break;

                    case 1:
                        // 收料退库单
                        break;

                    case 2:
                        // 生产退料单
                        break;

                    case 3:
                        Msg = string.Empty;
                        string NO = info.TradeOrderNO;
                        object[] args = { NO, Msg };
                        falg = SyncData.BackToERP("", "BackProductionPickingOrder", args, out Msg);

                        // 生产领料单

                        break;

                    //case 4:
                    //    // 生产退料单
                    //    break;

                    case 5:
                        // 物料调拨单
                        // falg = bll.AccountWmsTradeOrderInfo_5(info, out Msg);
                        break;

                    case 6:
                        // 其他领料单
                        break;

                    case 7:
                        // 其他入库单
                        break;

                    case 8:
                        // 生产缴库单
                        break;

                    case 9:
                        // 生产退库单
                        break;

                    case 10:
                        // 销售出库单
                        break;

                    case 11:
                        // 销售退库单
                        break;

                    case 12:
                        // 盘盈盘库单
                        break;

                    default:
                        // 处理未知类型的交易单
                        break;
                }
                if (falg)
                    return Ok();
                else
                    return Content(HttpStatusCode.InternalServerError, Msg);
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }

        /// <summary>
        /// 依据仓储料批查询库存物料
        /// </summary>
        /// <param name="MaterialNO"></param>
        /// <param name="WarehouseNO"></param>
        /// <param name="BatchNO"></param>
        /// <param name="StorageNO"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("StockMaterialQuery")]  // 组合路由: /api/WMS/StockMaterialQuery
        public IHttpActionResult StockMaterialQuery(
        string MaterialNO = "",
        string WarehouseNO = "",
        string BatchNO = "",
        string StorageNO = ""
        )
        {
            string Msg = string.Empty;
            Sql sql = new Sql();
            List<WmsStockMaterial> list = new List<WmsStockMaterial>();
            var lists = "";
            try
            {
                WmsStockMaterialBLL bll = new WmsStockMaterialBLL();
                sql = new Sql();
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where ( BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%')");
                }
                if (!string.IsNullOrEmpty(BatchNO))
                {
                    sql.Append("Where ( WmsStockMaterial.BatchNO Like '%" + BatchNO + "%')");
                }
                if (!string.IsNullOrEmpty(StorageNO))
                {
                    sql.Append("Where (BasStorageInfo.StorageNO Like '%" + StorageNO + "%')");
                }
                if (!string.IsNullOrEmpty(WarehouseNO))
                {
                    sql.Append("Where (BasWarehouseInfo.WarehouseNO = '" + WarehouseNO + "')");
                }

                list = bll.NotPagedQuery(sql, out Msg, "BasMaterialInfo.MaterialNO, WmsStockMaterial.BatchNO,BasWarehouseInfo.WarehouseNO,BasStorageInfo.StorageNO");
                var json = ConvertJson<WmsStockMaterial>.ListToJson(list);
                lists = "{\"total\":" + list.Count + ",\"rows\":" + json + "}";
                return Ok(lists);
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, new { total = -1, rows = new List<object>(), Message = ex.ToString() });
            }
        }

        /// <summary>
        /// 更改仓储料批
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage ChanegTradeSouece([FromBody] WmsTradeSource info)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<object>();
            StringBuilder sb = new StringBuilder();
            Database db = DB.D();
            db.BeginTransaction();
            try
            {
                Sql sql = new Sql();
                string strSql = "Update WmsTradeSource  set StorageID='{0}',MaterialID='{1}',BatchNO='{2}' where TradeSourceID='{3}'";
                if (!string.IsNullOrEmpty(info.StorageID) && !string.IsNullOrEmpty(info.MaterialID) && !string.IsNullOrEmpty(info.BatchNO) && !string.IsNullOrEmpty(info.TradeSourceID))
                {
                    sql.Append(string.Format(strSql, info.StorageID, info.MaterialID, info.BatchNO, info.TradeSourceID));
                }
                if (sql.SQL.Length > 0)
                {
                    int res = db.Execute(sql.SQL);
                }
                db.CompleteTransaction();
            }
            catch (Exception ex)
            {
                db.AbortTransaction();
                json.Message = ex.ToString();
                json.Code = 500;
            }
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }
    }
}